<template>
  <div class="collection-panel">
    <!-- 合集列表 -->
    <div class="collection-list">
      <div class="panel-header">
        <h3>合集管理</h3>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          @click="showCreateDialog = true"
        >
          新建合集
        </el-button>
      </div>

      <div class="collection-items" v-loading="loading">
        <div
          v-for="collection in collections"
          :key="collection.id"
          class="collection-item"
          :class="{ disabled: !collection.isEnabled }"
        >
          <div class="item-header">
            <div class="item-info">
              <span
                class="collection-dot"
                :style="{ backgroundColor: collection.color }"
              ></span>
              <span class="collection-name" :title="collection.name">{{ collection.name }}</span>
              <el-dropdown trigger="click" @command="handleCommand">
                <i class="el-icon-more el-icon--right action-icon"></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{action: 'edit', id: collection.id}">
                    <i class="el-icon-edit"></i> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'delete', id: collection.id}">
                    <i class="el-icon-delete"></i> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          <div class="item-footer">
            <div class="item-stats">
              <el-tag size="mini" type="info" class="article-count">
                {{ collection.articleCount || 0 }} 篇文章
              </el-tag>
            </div>
            <div class="item-controls">
              <el-switch
                v-model="collection.isEnabled"
                size="mini"
                @change="toggleCollectionStatus(collection)"
              />
            </div>
          </div>
          <div v-if="collection.description" class="item-description">
            {{ collection.description }}
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && collections.length === 0" class="empty-state">
          <i class="el-icon-folder-opened"></i>
          <p>暂无合集</p>
          <el-button type="text" @click="showCreateDialog = true">
            创建第一个合集
          </el-button>
        </div>
      </div>
    </div>

    <!-- 创建/编辑合集对话框 -->
    <el-dialog
      :title="isEditing ? '编辑合集' : '新建合集'"
      :visible.sync="showCreateDialog"
      width="500px"
      :close-on-click-modal="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      center
      @close="resetForm"
    >
      <el-form
        ref="collectionForm"
        :model="formData"
        :rules="formRules"
        label-width="80px"
        size="small"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入合集名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入合集描述"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="颜色" prop="color">
          <el-color-picker
            v-model="formData.color"
            :predefine="predefineColors"
            size="medium"
            color-format="hex"
          />
        </el-form-item>

        <el-form-item label="图标" prop="icon">
          <el-input
            v-model="formData.icon"
            placeholder="请输入图标名称（可选）"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
            v-model="formData.sortOrder"
            :min="0"
            :max="9999"
            size="small"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="状态" prop="isEnabled">
          <el-switch
            v-model="formData.isEnabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
          :loading="submitting"
        >
          {{ isEditing ? '更新' : '创建' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <confirm-dialog
      :visible="showDeleteDialog"
      title="删除合集"
      :message="deleteDialogContent"
      @confirm="confirmDelete"
      @cancel="showDeleteDialog = false"
    />
  </div>
</template>

<script>
import { collectionApi } from '@/api/collections'
import ConfirmDialog from '@/components/common/ConfirmDialog'

export default {
  name: 'CollectionPanel',

  components: {
    ConfirmDialog
  },

  data() {
    return {
      loading: false,
      submitting: false,
      collections: [],

      // 对话框状态
      showCreateDialog: false,
      showDeleteDialog: false,
      isEditing: false,
      currentEditId: null,
      deleteTargetId: null,

      // 表单数据
      formData: {
        name: '',
        description: '',
        color: '#67C23A', // 修改默认颜色为绿色，便于测试
        icon: '',
        sortOrder: 0,
        isEnabled: true
      },

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入合集名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ],
        description: [
          { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
        ],
        sortOrder: [
          { type: 'number', min: 0, max: 9999, message: '排序值范围为 0-9999', trigger: 'blur' }
        ]
      },

      // 预定义颜色
      predefineColors: [
        '#409EFF', '#67C23A', '#E6A23C', '#F56C6C',
        '#909399', '#C0C4CC', '#8E44AD', '#3498DB',
        '#2ECC71', '#F39C12', '#E74C3C', '#95A5A6'
      ]
    }
  },

  computed: {
    deleteDialogContent() {
      const collection = this.collections.find(c => c.id === this.deleteTargetId)
      if (!collection) return ''
      return `确定要删除合集"${collection.name}"吗？删除后将无法恢复。`
    }
  },

  async created() {
    await this.loadCollections()
  },

  methods: {
    // 加载合集列表
    async loadCollections() {
      this.loading = true
      try {
        this.collections = await collectionApi.getAll()
      } catch (error) {
        this.$message.error('加载合集列表失败: ' + error.message)
        console.error('加载合集列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 切换合集状态
    async toggleCollectionStatus(collection) {
      try {
        await collectionApi.toggleStatus(collection.id, collection.isEnabled)
        this.$message.success(collection.isEnabled ? '合集已启用' : '合集已禁用')
        await this.loadCollections()
      } catch (error) {
        // 恢复状态
        collection.isEnabled = !collection.isEnabled
        this.$message.error('更新合集状态失败: ' + error.message)
        console.error('更新合集状态失败:', error)
      }
    },

    // 处理下拉菜单命令
    handleCommand(command) {
      if (command.action === 'edit') {
        this.editCollection(command.id)
      } else if (command.action === 'delete') {
        this.deleteCollection(command.id)
      }
    },

    // 编辑合集
    async editCollection(id) {
      try {
        const collection = await collectionApi.getById(id)
        this.isEditing = true
        this.currentEditId = id
        this.formData = {
          name: collection.name,
          description: collection.description || '',
          color: collection.color || '#409EFF',
          icon: collection.icon || '',
          sortOrder: collection.sortOrder || 0,
          isEnabled: collection.isEnabled !== false
        }
        this.showCreateDialog = true
      } catch (error) {
        this.$message.error('获取合集信息失败: ' + error.message)
        console.error('获取合集信息失败:', error)
      }
    },

    // 删除合集
    deleteCollection(id) {
      this.deleteTargetId = id
      this.showDeleteDialog = true
    },

    // 确认删除
    async confirmDelete() {
      try {
        await collectionApi.delete(this.deleteTargetId)
        this.$message.success('合集删除成功')
        this.showDeleteDialog = false
        this.deleteTargetId = null
        await this.loadCollections()
      } catch (error) {
        this.$message.error('删除合集失败: ' + error.message)
        console.error('删除合集失败:', error)
      }
    },

    // 提交表单
    async submitForm() {
      const valid = await this.$refs.collectionForm.validate().catch(() => false)
      if (!valid) return

      this.submitting = true
      try {
        // 添加调试信息
        console.log('提交的表单数据:', this.formData)
        console.log('颜色值:', this.formData.color)
        
        if (this.isEditing) {
          await collectionApi.update(this.currentEditId, this.formData)
          this.$message.success('合集更新成功')
        } else {
          const result = await collectionApi.create(this.formData)
          console.log('创建合集返回结果:', result)
          this.$message.success('合集创建成功')
        }

        this.showCreateDialog = false
        await this.loadCollections()
      } catch (error) {
        this.$message.error((this.isEditing ? '更新' : '创建') + '合集失败: ' + error.message)
        console.error('提交合集失败:', error)
      } finally {
        this.submitting = false
      }
    },

    // 重置表单
    resetForm() {
      this.isEditing = false
      this.currentEditId = null
      this.formData = {
        name: '',
        description: '',
        color: '#67C23A', // 修改默认颜色为绿色，便于测试
        icon: '',
        sortOrder: 0,
        isEnabled: true
      }
      this.$refs.collectionForm?.clearValidate()
    },

    // 验证合集名称
    async validateName(rule, value, callback) {
      if (!value) {
        callback()
        return
      }

      try {
        const exists = await collectionApi.checkNameExists(value, this.currentEditId)
        if (exists) {
          callback(new Error('合集名称已存在'))
        } else {
          callback()
        }
      } catch (error) {
        callback(new Error('验证合集名称失败'))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.collection-panel {
  height: 100%;
  display: flex;
  flex-direction: column;

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #ebeef5;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .collection-items {
    flex: 1;
    padding: 8px;
    overflow-y: auto;

    .collection-item {
      margin-bottom: 8px;
      padding: 12px;
      border: 1px solid #ebeef5;
      border-radius: 6px;
      background: #fff;
      transition: all 0.3s ease;

      &:hover {
        border-color: #c6e2ff;
        background-color: #f0f9ff;
      }

      &.disabled {
        opacity: 0.6;
        background-color: #f5f7fa;
      }

      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .item-info {
          display: flex;
          align-items: center;
          flex: 1;
          min-width: 0;

          .collection-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
            flex-shrink: 0;
          }

          .collection-name {
            font-weight: 500;
            color: #303133;
            margin-right: 8px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            flex: 1;
          }

          .action-icon {
            cursor: pointer;
            color: #909399;
            transition: color 0.3s ease;
            margin-left: auto;

            &:hover {
              color: #409eff;
            }
          }
        }
      }

      .item-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;

        .item-stats {
          display: flex;
          align-items: center;

          .article-count {
            font-size: 12px;
          }
        }

        .item-controls {
          display: flex;
          align-items: center;
        }
      }

      .item-description {
        font-size: 12px;
        color: #909399;
        line-height: 1.4;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 16px;
      color: #c0c4cc;
    }

    p {
      margin: 0 0 16px 0;
      font-size: 14px;
    }
  }
}

// 下拉菜单样式
:deep(.el-dropdown-menu__item) {
  i {
    margin-right: 8px;
  }
}

// 表单样式
:deep(.el-form-item) {
  margin-bottom: 18px;

  &:last-child {
    margin-bottom: 0;
  }
}

// 颜色选择器样式
:deep(.el-color-picker) {
  .el-color-picker__trigger {
    width: 40px !important;
    height: 40px !important;
    border-radius: 4px;
    display: flex !important;
    align-items: center;
    justify-content: center;
    
    .el-color-picker__color {
      width: 36px !important;
      height: 36px !important;
      border-radius: 3px;
      
      .el-color-picker__color-inner {
        width: 100% !important;
        height: 100% !important;
        border-radius: 3px;
      }
    }
    
    .el-color-picker__icon {
      display: none;
    }
  }
  
  // 确保颜色面板正常显示
  .el-color-picker__panel {
    z-index: 3100 !important;
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  z-index: 3000 !important;
  max-width: 90vw;
  margin: 5vh auto;
  
  .el-form-item__label {
    font-weight: 500;
  }
  
  .el-textarea__inner {
    font-family: inherit;
  }
  
  .el-dialog__header {
    padding: 20px 20px 10px;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .el-dialog__body {
    padding: 10px 20px 20px;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px;
    text-align: right;
  }
}

// 对话框遮罩层样式
:deep(.el-dialog__wrapper) {
  z-index: 3000 !important;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 确保弹窗在最顶层
:deep(.v-modal) {
  z-index: 2999 !important;
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95vw !important;
    margin: 2vh auto;
    
    .el-dialog__header,
    .el-dialog__body,
    .el-dialog__footer {
      padding-left: 15px;
      padding-right: 15px;
    }
  }
}
</style>